import {
  DrawerForm,
  ModalForm,
  ProForm,
  ProFormDatePicker,
  ProFormInstance,
  ProFormSegmented,

  ProFormSelect,

  ProFormTextArea,
  ProFormUploadDragger,
} from '@ant-design/pro-components';
import React, { useRef, useState } from 'react';
import './index.less'
import { Button, message } from 'antd';
import { fetchChannelUser } from '@/pages/DyCps/service';
import { request } from 'umi';
import moment from 'moment';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.RuleListItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: any) => void;
  onSubmit: (values: any) => Promise<void>;
  onUpdate: (values: any) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<API.RuleListItem>;
};

const UpdateFormDy: React.FC<UpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [updateType, setUpdateType] = useState<any>('excel');
  const [channel,setChannel] =useState<any>('');
  const [date,setDate] = useState<any>('');
  return (
    <DrawerForm
      title="跟单"
      width="620px"
      formRef={formRef}
      visible={props.updateModalVisible}
      onVisibleChange={(val) => {
        if (!val) {
          props.onCancel();
        }
       
      }}
      onFinish={async (val) => {
        let orders = val.orders;
        if('\n'.indexOf(orders)) {
          orders = orders.split('\n')
        } else {
          return message.error("订单格式有误~")
        }
        
        props.onSubmit({ ...val, orders, date });
      }}
    >
      <ProFormSegmented
        name="upType"
        label="选择跟单方式"
        onChange={(val)=>{
          setUpdateType(val);
        }}
        valueEnum={{
          excel: '上传excel',
          order: '批量订单号',
        }}
      />
      <ProForm.Group>
        <ProFormSelect
          name="channel"
          label="推广渠道"
          width='sm'
          request={async () => {
            const rsp = await fetchChannelUser({});
            if(rsp.code ==="SUCCESS") {
              return rsp.data;
            }
            return []
          }}
          onChange={(val)=>{
            setChannel(val);
          }}
          placeholder="请输入产品渠道"
          rules={[{ required: true, message: '产品渠道不能为空!' }]}
        />
        <ProFormDatePicker
          label="跟单的开始时间"
          width='sm'
          name='date'
           tooltip="不选,默认从前3天开始跟单"
          onChange={(val)=>{
            const date = moment(new Date(val)).format('YYYY-MM-DD HH:mm:ss');
            setDate(date);
          }}
        >
        </ProFormDatePicker>
      </ProForm.Group>
      {updateType === "excel" ? 
      
      <ProForm.Group>
      <ProFormUploadDragger
        max={1}
        fieldProps={{
          name: 'file',
          data: {
            token:localStorage.getItem('token'),
            channel: channel,
            date: date
          },
          beforeUpload: (file, fileList) =>{
            if(channel === '' ) {
              message.error("渠道必须")
              return false
            }
          },
          customRequest: async ({ file, data, onProgress, onSuccess, onError }) => {
            const formData = new FormData();
            formData.append('file', file);
            
            // 添加额外参数
            if (data) {
              Object.keys(data).forEach((key) => {
                formData.append(key, data[key]);
              });
            }
      
            try {
              // 调用 umi request 并配置超时
              const response = await request('/api/uploadDyFileDiff2', {
                method: 'POST',
                data: formData,
                timeout: 500000, // 设置超时时间为 300 秒（单位：毫秒）
                requestType: 'form', // 明确指定表单格式
                onUploadProgress: (e) => {
                  if (e.lengthComputable) {
                    const percent = Math.round((e.loaded / e.total) * 100);
                    onProgress({ percent }, file);
                  }
                },
              });
      
              // 手动触发成功回调
              onSuccess(response, file);
            } catch (error) {
              // 处理超时和其他错误
              onError(error, file);
            }
          },
          onChange: (info) => {
            const { status, response } = info.file;
            if (status === 'done') {
              if (response?.code === 'SUCCESS') {
                props.onUpdate(response.data);
              }
            } else if (status === 'error') {
              message.error(`上传失败: ${info.file.response?.message || '未知错误'}`);
            }
          },
        }}
        label="选择跟单文件格式【.xls/.xlsx】"
      />  
        <ModalForm
          title="订单导入数据"
          trigger={<Button>示例</Button>}
          submitter={false}
        >
          <table className="com_table">
            <tr>
                <th>订单号</th>
                <th>付款金额</th>
                <th>图片地址</th>
            </tr>
            <tr>
                <td>1111</td>
                <td>2222</td>
                <td>图片地址（可选填）</td>
            </tr>
            <tr>
                <td>1111</td>
                <td>2222</td>
                <td>数据2-3</td>
            </tr>
           
        </table>
        </ModalForm>
      </ProForm.Group>: 
      <ProFormTextArea
        width="md"
        name="orders"
        label="订单号"
        placeholder="请输入多个订单号,用逗号或回车分割"
        rules={[{ required: true, message: '订单称不能为空!' }]}
      />
    }
   
    </DrawerForm>
  );
};

export default UpdateFormDy;
